package com.zzyl.service.impl;

import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.service.MemberService;
import com.zzyl.service.WeChatService;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private WeChatService weChatService;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    private static List<String> DEFAULT_NICKNAME_PREFIX = List.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        LoginVo lv = new LoginVo();
        // 获取openId
        String openId = weChatService.getOpenId(userLoginRequestDto.getCode());
        String phone = weChatService.getPhone(userLoginRequestDto.getPhoneCode());
        // 通过openid去数据库中查询，是否有该用户
        Member member = memberMapper.getMemberByOpenId(openId);

        // 判断获取的用户是否为空，则表示为新用户，插入数据
        if (member == null) {
            member = new Member();
            member.setOpenId(openId);
            member.setPhone(phone);

            // 随记生成一个昵称
            String name = DEFAULT_NICKNAME_PREFIX.get(new Random().nextInt(DEFAULT_NICKNAME_PREFIX.size()));
            name = name + "_" + phone.substring(7);
            member.setName(name);
            lv.setNickName(name);
            // 调用插入方法
            memberMapper.insertMember(member);  // 新用户注册
        } else {
            // 如果不为空，判断新获取的手机号码，与查出来的手机号码是否一致
            if (!phone.equals(member.getPhone())) {
                // 如果不一致，则表示手机号码不一致，修改member表中数据
                member.setPhone(phone);
                memberMapper.updateMember(member);  // 修改登录的手机号码
            }
            // 把查出来的member对象中的昵称给LoginVo对象
            lv.setNickName(member.getName());
        }
        // 如果一致，则表示是老用户，直接返回token
        // 生成token令牌
        Map map = new HashMap();
        map.put("id", member.getId());
        map.put("nickName", member.getName());
        String token = JwtUtil.createJWT(
                jwtTokenManagerProperties.getBase64EncodedSecretKey(),
                jwtTokenManagerProperties.getTtl(),
                map);
        lv.setToken(token);
        return lv;
    }
}